// pages/jqq/index.js
Page({
	async showModal() { //显示模态对话框
		await wx.showModal({
			content: '读取数据错误~',
			showCancel:false,
		})
	},
	async onReachBottom() { //触底加载更多的列表信息
		let url, mi = this.data.menuIndex //当前菜单对象的索引号
		let menu = this.data.menus[mi] //获取当前菜单对象
		let type = menu.types[menu.typeIndex] //获取类型对象
		if (type.nextPage == null) type.nextPage = 1
		if (type.nextPage == -1) return
		let videos = null
		if (mi == 1) { // https://jqqzx.cc/vodsearch杀死/page/2.html
			if (this.data.key) {
				url = `${this.addr}/vodsearch${encodeURIComponent(this.data.key)}/page/${type.nextPage}.html` //实现搜索的网址
			} else {
				return
			}
			videos = await this.getTypeList(null, url)
		} else {
			videos = await this.getTypeList(type)
		}
		console.log(555, videos)
		// let html = await this.ajax({url}) //返回的文本信息
		if (videos != null) {
			let r, change = {},
				index = type.videos.length //存储找到的视频信息
			if (videos.length > 0) {
				for (let i = 0; i < videos.length; ++i) {
					change['menus[' + mi + '].types[' + menu.typeIndex + '].videos[' + index + ']'] = videos[i]
						++index
				}
			}
			change['menus[' + mi + '].types[' + menu.typeIndex + '].nextPage'] = videos.length == 0 ? -1 : type.nextPage + 1
			this.setData(change)
		} else {
			wx.showModal({
				showCancel: false,
				content: '读取数据失败，请重新尝试~',
			})
		}

	},
	setPath(url) {
		this.header.path = url.substring(this.addr.length)
	},
	ajax(e) { //获取网页的文本信息， 支持以 Promise 风格来调用, e={url, timeout}

		return new Promise((resolve, reject) => { //resolve-成功时的回调函数，reject-失败时的回调函数
			wx.showLoading({ //显示等待消息框，不支持以 Promise 风格来调用：
				title: '请稍等...',
				mask: true, //显示透明蒙层，避免触摸穿透
			})
			if (e.header) this.setPath(e.url)
			wx.request({ //发起请求
				url: e.url, //网址
				timeout: e.timeout || 25000, //超时时间
				// header: e.header||{},
				complete: (r) => { //执行结果
					wx.hideLoading() //隐藏消息框
					// console.log(r) //{errMsg: "request:fail ", statusCode: 200, data:'xxx'} errMsg: "request:fail timeout"
					if (r.errMsg == 'request:ok' && r.statusCode == 200) { //成功获得数据
						let html = r.data //返回的文本信息
						resolve(html)
					} else { //否则，返回空字符串
						console.log(e)
						resolve(null)
					}
				}
			})
		})
	},
	onHide() { //页面
		// console.log('onHide')
		if (!this.data.hasSave) {
			this.data.hasSave = true
			wx.setStorageSync('jqq', this.data) //保存数据到手机缓存中
		}
	},
	onUnload() {
		console.log('onUnload')
		// wx.setStorageSync('xuanfeng', this.data) //保存数据到手机缓存
		if (!this.data.hasSave) {
			this.data.hasSave = true
			wx.setStorageSync('jqq', this.data) //保存数据到手机缓存中
		}
	},
	onLoad(e) {
		this.addr = 'https://jqqzx.cc'
		let d = wx.getStorageSync('jqq') //读取缓存的数据
		// console.log(d)
		if (d && d.menus.length>4) { //原来讲课只有4个菜单项，则忽略原有数据
			this.setData(d) //若存在，则设置为新的页面数据
		}
	},
	play(e) {
		let index = e.currentTarget.dataset.index //获取点击视频的索引号
		wx.navigateTo({
			url: 'player?index=' + index,
		})
	},
		this.setData(change)
	async longmenu(e) {
		let menuIndex = e.target.dataset.index //点击菜单的索引号
		console.log(111, e)
		if (menuIndex == 0) { //长按的是刷新
			let r = await wx.showModal({
				content: '确信要重新更新菜单吗~',
			})
			if (r.confirm) {
				this.data = {}
				wx.navigateBack()
			}
		}
	},
	async menus(e) { //点击菜单的操作
		let oldmenuIndex = this.data.menuIndex //原来的菜单对象的索引号
		let menuIndex = e.target.dataset.index //点击菜单的索引号

		let change = {
				hasSave: false
			},
			videos = null
		if (menuIndex == 0) { //点击是刷新
			if (oldmenuIndex == 1 && this.data.menus[1].types[0].videos.length > 0) return //搜索的内容无需刷新
			if (oldmenuIndex == 1) { //对搜索的刷新
				this.search()
			} else {
				let menu = this.data.menus[oldmenuIndex] //获取当前菜单对象
				if (menu.typeIndex == null) {
					wx.showModal({
						showCancel: false, //不再显示取消按钮
						content: '必须先选择视频类型~',
					})
					return
				}
				let typeIndex = menu.typeIndex
				let type = menu.types[menu.typeIndex] //获取当前的类型对象
				type.nextPage = 1
				videos = await this.getTypeList(type)
				// console.log('videos=',videos)
				change['menus[' + oldmenuIndex + '].types[' + typeIndex + '].videos'] = videos //存储找到的视频信息到每个类型下
				change['menus[' + oldmenuIndex + '].types[' + typeIndex + '].nextPage'] = 2 //触底加载更多时的页面
			}
		} else {
			if (menuIndex == oldmenuIndex) return //和上次点击的相同，直接返回
			change.menuIndex = menuIndex //记录新点击项的索引号
			change['menus[' + oldmenuIndex + '].selected'] = false //取消原来菜单的选择状态
			change['menus[' + menuIndex + '].selected'] = true //设置新点击项的选择状态
		}
		this.setData(change) //更新页面显示
	},
	async search(e) {
		let key
		if (e) key = e.detail.value.trim() //要搜索的关键词
		else key = this.data.key //从页面数据中来获取搜索的关键词
		if (!key) {
			wx.showModal({
				showCancel: false, //不再显示取消按钮
				content: '必须输入搜索的关键词~',
			})
			return
		}
		if (key != this.data.key) {
			let change = {
				key,
				hasSave: false,
				'menus[1].types[0].nextPage': null,
				'menus[1].types[0].videos': [],
			}
			this.setData(change, () => {
				this.onReachBottom()
			})
		}
	},
	onUnload(){ //页面退出时执行
		wx.setStorageSync('jqq', this.data)
	async getTypeList(type, url) {
		if (url == null) {
			let p = type.nextPage
			if (p == null) p = 1 //页码没有定义，默认是第1页
			if (p == -1) return [] //已经没有更多页，则直接返回
			url = `${this.addr}/vodshow/${type.id}/page/${p}.html`
		}
		let html = await this.ajax({
			url,
		}) //返回的文本信息 herder:this.header
		if (html == null) return null
		
		let regex = /<a href="(\/vod[^"]+)" title="([^"]+)".+?data-original="([^"]+)"|<a href="(\/vod[^"]+)" class="module-card-item-poster">.+?data-original="([^"]+)" alt="([^"]+)/gs
		let r, list = [] //用来存储找到的所有电影信息
		while (r = regex.exec(html)) {
			list.push({
				url: r[1]||r[4], //视频超链接
				img: r[3]||r[5], //图片地址
				title: r[2]||r[6], //视频的标题
			})
		}
		return list
	},
	async types(e) { //点击类型时的操作， await和async必须配对使用
		let typeIndex = e.target.dataset.index //点击类型的索引号
		if (typeIndex == null) return
		let menuIndex = this.data.menuIndex
		let menu = this.data.menus[menuIndex] //当前选择的菜单项
		let change = {
			hasSave: false
		} //记录要修改的页面数据
		if (menu.typeIndex != undefined) {
			if (menu.typeIndex == typeIndex) return //点击的类型和原来的相同，就不再处理，直接返回
			change['menus[' + menuIndex + '].types[' + menu.typeIndex + '].selected'] = false //取消原来类型的选择状态
		}
		change['menus[' + menuIndex + '].types[' + typeIndex + '].selected'] = true //设置新选择类型的选择状态
		change['menus[' + menuIndex + '].typeIndex'] = typeIndex //设置新点击的索引号
		this.setData(change) //更新界面实现类型的点击效果
		let type = menu.types[typeIndex] //获取类型对象
		if (!(type.videos && type.videos.length > 0)) { //该类型下尚没有数据
			let videos = await this.getTypeList(type)
			if (videos == null) {
				this.showModal()
			} else {
				change = {}
				if (videos.length > 0) {
					change['menus[' + menuIndex + '].types[' + typeIndex + '].videos'] = videos //存储找到的视频信息到每个类型下
					change['menus[' + menuIndex + '].types[' + typeIndex + '].nextPage'] = 2 //触底加载更多时的页面
				} else {
					change['menus[' + menuIndex + '].types[' + typeIndex + '].nextPage'] = -1 //没有视频
				}
				this.setData(change)
			}
		}
	},
	data: {
		menuIndex: 2,
		menus: [{
			menu: '[刷新]'
		}, {
			menu: '[搜索]',
			types: [{
				videos: []
			}],
			typeIndex: 0,
		}, {
			menu: '电影',
			selected: true,
			types: [
				{ type: '动作片', id:'id/dongzuopian' },
				{ type: '喜剧片', id:'id/xijupian' },
				{ type: '爱情片', id:'id/aiqingpian' },
				{ type: '科幻片', id:'id/kehuanpian' },
				{ type: '恐怖片', id:'id/kongbupian' },
				{ type: '剧情片', id:'id/juqingpian' },
				{ type: '战争片', id:'id/zhanzhengpian' },
				{ type: '动画片', id:'id/donghuapian' },
			],
		},
		{
			menu: '电视剧',
			types: [
				{ type: '国产剧', id:'id/guochanju' },
				{ type: '港台剧', id:'id/gangtaiju' },
				{ type: '日韩剧', id:'id/rihanju' },
				{ type: '欧美剧', id:'id/oumeiju' },
				{ type: '泰国剧', id:'id/taiguoju' },
			],
		},
		{
			menu: '综艺',
			types: [
				{ type: 'Netflix', id:'class/Netflix/id/zongyi' },
				{ type: '真人秀', id:'class/%E7%9C%9F%E4%BA%BA%E7%A7%80/id/zongyi' },
				{ type: '音乐', id:'class/%E9%9F%B3%E4%B9%90/id/zongyi' },
				{ type: '喜剧', id:'class/%E5%96%9C%E5%89%A7/id/zongyi' },
				{ type: '脱口秀', id:'class/%E8%84%B1%E5%8F%A3%E7%A7%80/id/zongyi' },
				{ type: '文化', id:'class/%E6%96%87%E5%8C%96/id/zongyi' },
				{ type: '美食', id:'class/%E7%BE%8E%E9%A3%9F/id/zongyi' },
			]
		},
		{
			menu: '动漫',
			types: [
				{ type: 'Netflix', id:'class/Netflix/id/dongman' },
				{ type: '奇幻', id:'class/%E5%A5%87%E5%B9%BB/id/dongman' },
				{ type: '动作', id:'class/%E5%8A%A8%E4%BD%9C/id/dongman' },
				{ type: '科幻', id:'class/%E7%A7%91%E5%B9%BB/id/dongman' },
				{ type: '喜剧', id:'class/%E5%96%9C%E5%89%A7/id/dongman' },
				{ type: '冒险', id:'class/%E5%86%92%E9%99%A9/id/dongman' },
				{ type: '后宫', id:'class/%E5%90%8E%E5%AE%AB/id/dongman' },
				{ type: '爱情', id:'class/%E7%88%B1%E6%83%85/id/dongman' },
				{ type: '悬疑', id:'class/%E6%82%AC%E7%96%91/id/dongman' },
				{ type: '机战', id:'class/%E6%9C%BA%E6%88%98/id/dongman' },
				{ type: '战争', id:'class/%E6%88%98%E4%BA%89/id/dongman' },
				{ type: '其他', id:'class/%E5%85%B6%E4%BB%96/id/dongman' },
			]
		}],
	},
})